﻿using System;
using System.Drawing;
using System.Globalization;
using System.IO;

namespace SuperiorCommon
{
    public class LiteralCaptcha
    {
        /// <summary>
        /// 字段_width
        /// </summary>
        private readonly int _width;

        /// <summary>
        /// 字段_height
        /// </summary>
        private readonly int _height;

        /// <summary>
        /// 数量
        /// </summary>
        private readonly int _charCount;

        /// <summary>
        /// Initializes a new instance of the <see cref="LiteralCaptcha"/> class.
        /// </summary>
        /// <param name="width">The width</param>
        /// <param name="height">The height</param>
        /// <param name="charCount">The charCount</param>
        public LiteralCaptcha(int width, int height, int charCount)
        {
            _width = width;
            _height = height;
            _charCount = charCount;
        }

        /// <summary>
        /// 字段_captcha
        /// </summary>
        private string _captcha;

        /// <summary>
        /// Gets the captcha.
        /// </summary>
        public string Captcha
        {
            get
            {
                if (!string.IsNullOrEmpty(_captcha)) return _captcha;

                var rnd = new Random();
                var number = rnd.Next((int)Math.Pow(10, _charCount));
                _captcha = number.ToString(CultureInfo.InvariantCulture).PadLeft(_charCount, '0');
                return _captcha;
            }
        }

        /// <summary>
        /// Gets the result.
        /// </summary>------
        public string Result
        {
            get { return Captcha; }
        }

        /// <summary>
        /// The method will 
        /// </summary>
        public byte[] Generate()
        {
            using (var ms = new MemoryStream())
            {
                using (var bmp = new Bitmap(_width, _height))
                {
                    using (var g = Graphics.FromImage(bmp))
                    {
                        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                        g.FillRectangle(Brushes.WhiteSmoke, new Rectangle(0, 0, bmp.Width, bmp.Height));

                        g.DrawString(Captcha, new Font("微软雅黑", 20), Brushes.Gray, 18, 8);

                        const int c = 40;
                        var rand = new Random();
                        for (var i = 0; i < c; i++)
                        {
                            var x = rand.Next(_width);
                            var y = rand.Next(_height);
                            g.DrawRectangle(Pens.Gray, x, y, 1, 1);
                        }

                        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                        return ms.ToArray();
                    }
                }
            }
        }
    }
}
